<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <!-- dataForm.productLineName -->
          <el-form-item  label="产品线">
            <el-select v-model="dataForm.productLineId" style="width:100%" placeholder="请选择产品线">
              <el-option
                v-for="item in carShopList"
                :key="item.id"
                :label="item.productLineName"
                :value="item.id">
              </el-option>
            </el-select>
            <!-- <el-input
            readonly
              v-model=""
              placeholder="请选择产品线"
            ></el-input> -->
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12" :offset="0">
          <el-form-item  label="品牌id">
            <el-input
              v-model="dataForm.brandId"
         
              :placeholder="$t('user.username')"
            ></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="12" :offset="0">
          <el-form-item  label="品牌名称">
            <el-input
              v-model="dataForm.brandChn"
           
              
              placeholder="请输入品牌名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item  label="品牌名称简称">
            <el-input
              v-model="dataForm.brandEng"
        
              placeholder="请输入品牌名称简称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item  label="车系名称">
            <el-input v-model="dataForm.branchChn"  placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item  label="车系名称简称">
            <el-input v-model="dataForm.branchEng"  placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12" :offset="0">
          <el-form-item  label="车型名称">
            <el-input v-model="dataForm.vdsName" readonly placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item  label="车型中文简称">
            <el-input v-model="dataForm.vdsNameChn" readonly placeholder=""></el-input>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12" :offset="0">
          <el-form-item  label="车型英文简称">
            <el-input
              v-model="dataForm.vdsNameEng"
              readonly
              placeholder="$t('user.vdsNameEng')"
            ></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="12" :offset="0">
          <el-form-item prop="status" label="状态" size="mini">
            <el-radio-group v-model="dataForm.status">
              <el-radio label="0">隐藏</el-radio>
              <el-radio label="1">显示</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" :offset="0">
          <el-form-item  label="图片" class="role-list">
            <el-upload
										action="#"
										:class="{hide:hideUpload}"
										:limit="1"
										:auto-upload="false"
										list-type="picture-card"
										:on-preview="handlePictureCardPreview"
										:on-change="imgChange" 
										:file-list="fileList"
										:multiple='false'
										:on-remove="handleRemove">
										<i class="el-icon-plus"></i>
									</el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-button @click="oncancel()">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from "lodash/debounce";
import { isEmail, isMobile } from "@/utils/validate";
export default {
  data() {
    return {
      visible: false,
      roleList: [],
      hideUpload:false,
      roleIdListDefault: [],
      carShopList:[],
      fileList:[],
      dataForm: {
        id: "",
        brandId: "",
        brandChn: "",
        brandEng: "",
        branchChn: "",
        branchEng: "",
        vdsName: "",
        vdsNameChn: 0,
        vdsNameEng: "",
        status: "0",
        branchImage:"",
        productLineId:""
      },
    };
  },
  computed: {
    dataRule() {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        callback();
      };
      var validateConfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t("validate.required")));
        }
        if (this.dataForm.password !== value) {
          return callback(new Error(this.$t("user.validate.confirmPassword")));
        }
        callback();
      };
      var validateEmail = (rule, value, callback) => {
        if (value && !isEmail(value)) {
          return callback(
            new Error(
              this.$t("validate.format", { attr: this.$t("user.email") })
            )
          );
        }
        callback();
      };
      var validateMobile = (rule, value, callback) => {
        if (value && !isMobile(value)) {
          return callback(
            new Error(
              this.$t("validate.format", { attr: this.$t("user.mobile") })
            )
          );
        }
        callback();
      };
      return {
        username: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        deptName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        password: [{ validator: validatePassword, trigger: "blur" }],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
        realName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      };
    },
  },
  created(){
  
  },
  methods: {
    oncancel(){
      this.visible = false
      this.$emit('canCle')
    },
    handleRemove(){
      this.dataForm.branchImage = "";
      setTimeout(()=>{
        this.hideUpload = false;
      })
    },
    imgChange(file, fileList){
				this.hideUpload = fileList.length > 0
				let fileUpLoad = file.raw
				this.uploadFile(fileUpLoad)
			},
    //放大图片
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
    //上传图片
    uploadFile(val, id) {
      let data = new FormData();
      data.append("file", val);
      var that = this;
      this.$http
        .post("sys/oss/upload", data, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(function (res) {
          if (res.data.code == 0) {
            that.dataForm.branchImage = res.data.data.src;
          } else {
            that.$notify({
              title: "失败",
              message: res.msg,
              type: "warning",
            });
          }
        });
    },
    init() {
      this.visible = true;
      this.dataForm.deptId = "";
      this.fileList = [];
      this.hideUpload = false;
      this.$nextTick(() => {
        this.getRoleList()
        this.$refs["dataForm"].resetFields();
        this.roleIdListDefault = [];
        // Promise.all([this.getRoleList()]).then(() => {
         
        // });
      });
    },
    // 获取静态资源
    getRoleList() {
      return this.$http
        .get("/productLine/page")
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.carShopList= res.data.list;
          if (this.dataForm.id) {
            this.getInfo();
          }
        })
        .catch(() => {});
    },
    // 获取信息
    getInfo() {
      this.$http
        .get(`/findbrandbranchvds/${this.dataForm.id}`)
        .then(({ data: res }) => {
          if (res.code!== 0) {
            return this.$message.error(res.msg);
          }
            
          Object.keys(this.dataForm).forEach(item=>{
                  console.log(item,'item')
              this.dataForm[item] = res.data[item] || ""
              if(item=='status'){
                this.dataForm[item] = String(res.data[item]) 
              }
          }) 
          console.log(this.dataForm,'this.dataForm')
          if(this.dataForm.branchImage){
              this.fileList.push(
                {
                  url:this.dataForm.branchImage
                }
              )
            this.hideUpload = true;	
          }
          console.log(this.dataForm,'this.dataForm')

        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          let url 
          if(!this.dataForm.id){
            url = 'findbrandbranchvds/save'
          }else{
            url = '/findbrandbranchvds/update'
          }
          this.$http.post(url, {
            ...this.dataForm,
          })
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.oncancel()
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {
              this.dataForm.status = String(this.dataForm.status)
            });
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>

<style lang="scss" scoped>
.hide ::v-deep .el-upload--picture-card {
		display: none !important;
	}
.mod-sys__user {
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
